package com.eascs.partner.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.eascs.afterloan.controller.O2oAfterLoanController;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.partner.form.PartnerQueryForm;
import com.eascs.partner.service.PartnerService;
import com.eascs.site.controller.BaseRestController;

@RestController
@RequestMapping("/partner/export/rest")
public class PartnerExportController extends BaseRestController {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private PartnerService partnerService;
	
	@RequestMapping("/partnerExport")
	public void dowanload(PartnerQueryForm params, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		PageResult<Object[]> pageResult=partnerService.queryExportByPage(params);
		String path = O2oAfterLoanController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/partner-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "合作方导出数据.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			defaultRowWriteHandler.setRowIndex(2);
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oAfterLoanController.class.getResourceAsStream("/excelTemplate/partner-model.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
	}
	
}
